#!/usr/local/bin/perl

$|++;

# This script is used to stress test the HTC server by forking off
# several children to each submit a request to the HTC Server.

use strict;
use Getopt::Long;
use Sys::Hostname;

# The way to pick the test or production HTC server instance is by
# picking the right library location.
use lib qw(/home/sgetest/lib);
use TIGR::HTCRequest;

my %options;
GetOptions( \%options, "children=i", "filename=s", "help" );

my $children = $options{children};
my $filename = $options{filename};

usage() if $options{help};

make_large_environment();
my $hostname = hostname;
my $pid = $$;

open (FH, "<", $filename) or die "Could not open filename.";
my $command = <FH>;
close FH;

for (my $child = 1; $child <= $children; $child++) {
    if (my $pid = fork) {
          # parent conroller.
    } else { # Child starts here
        die "cannot fork: $!" unless defined $pid;

        my $request = TIGR::HTCRequest->new( group => "antware",
                                             command => $command,
                                             getenv => 1,
                                           );
        my $id = $request->submit();
        print "Command \#${child} on $hostname got request id $id.";

        $request->wait_for_request();
        print "Command \#${child} on $hostname finished.";

        exit;
    }
}

sub usage {
    my $usage = <<"    _USAGE";
    --filename          File containing the command to run on 1 line.

    --children          The number of children to fork.
                        Each child will submit an HTC request to
                        run the configured command.
    _USAGE
    print $usage;
    exit 0;
}

sub make_large_environment {
    for (my $i = 1; $i <= 200; $i++) {
        my $varname = sprintf("N%03s", $i);
        $ENV{$varname} = "X" x 50;
    }
}

exit 0;
